package ar.republicagroup.gestion.view;

import ar.republicagroup.gestion.entities.Cheque;
import ar.republicagroup.gestion.entities.ChequeEstado;
import ar.republicagroup.gestion.entities.Cliente;
import ar.republicagroup.gestion.entities.CuentaBanco;
import ar.republicagroup.gestion.services.BancoServices;
import ar.republicagroup.gestion.services.BolsaChequeServices;
import ar.republicagroup.gestion.services.CalendarioBancarioServices;
import ar.republicagroup.gestion.services.ChequeEstadoServices;
import ar.republicagroup.gestion.services.ChequeServices;
import ar.republicagroup.gestion.services.ChequeTipoServices;
import ar.republicagroup.gestion.services.ClienteServices;
import ar.republicagroup.gestion.services.CuentaBancoServices;
import ar.republicagroup.gestion.services.LiquidacionServices;
import ar.republicagroup.gestion.util.AppSession;
import ar.republicagroup.gestion.util.JComboBoxModel;
import ar.republicagroup.gestion.util.SpringUtils;
import ar.republicagroup.gestion.util.helpers.FilterCheque;
import ar.republicagroup.gestion.util.helpers.Formato;
import ar.republicagroup.gestion.util.helpers.UserInterfaceHelper;
import ar.republicagroup.gestion.util.messages.UIMessages;
import static ch.lambdaj.Lambda.*;
import com.toedter.calendar.JDateChooser;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.Vector;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
import org.apache.log4j.Logger;


public class frmLiquidacion extends javax.swing.JFrame {

    private static Logger log               =  Logger.getLogger(frmLiquidacion.class);
    
    /* Services */
    CalendarioBancarioServices calendarioServices = (CalendarioBancarioServices)SpringUtils.getBean("calendarioBancarioServices");
    ChequeServices  chequeServices            = (ChequeServices)SpringUtils.getBean("chequeServices");
    ChequeEstadoServices chequeEstadoServices = (ChequeEstadoServices)SpringUtils.getBean("chequeEstadoServices");
    ClienteServices clienteServices           = (ClienteServices)SpringUtils.getBean("clienteServices");
    
    LiquidacionServices liquidacionServices   = (LiquidacionServices)SpringUtils.getBean("liquidacionServices");
    BancoServices bancoServices               = (BancoServices)SpringUtils.getBean("bancoServices");
    CuentaBancoServices cuentaBancoServices   = (CuentaBancoServices)SpringUtils.getBean("cuentaBancoServices");
      
    /* Listado */
    static List<Cheque> chequeList = new ArrayList<>();
    private List<Cheque> chequeFilteredList = new ArrayList<>();
    private static final int NOMBRE_CLIENTE = 4;
    
    
    private DefaultComboBoxModel modelComboBanco;
    private DefaultComboBoxModel modelComboCuenta;
    static JDateChooser calendar = new JDateChooser();
    
    private final int NO_EXISTE = -1;
    private final int CTA_SIN_ASIGNAR = 1;      
    private boolean fromTableClick = false;
    
    private Set<String> clientesToLiquid;
    
    /*Singleton */
    private static frmLiquidacion instance; 
   
    
    private frmLiquidacion() {
        initComponents();
        cargarDatos();
        valoresPorDefecto();
    }

    public static frmLiquidacion getInstance(){
        
        if(instance == null){
            instance = new frmLiquidacion();
        }    
    
        return instance;
    }

    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        panelContenedor = new javax.swing.JPanel();
        pnlCliente = new javax.swing.JPanel();
        comboClientes = new javax.swing.JComboBox();
        btnBuscar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblCheque = new javax.swing.JTable();
        btnLiquidar = new javax.swing.JButton();
        lblResultadoBuscar = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        lblFechaLiquidacion = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        lblTotalCAP = new javax.swing.JLabel();
        lblTotalVC = new javax.swing.JLabel();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel3 = new javax.swing.JPanel();
        chkEnableBanco = new javax.swing.JCheckBox();
        comboBanco = new javax.swing.JComboBox();
        chkCaja = new javax.swing.JCheckBox();
        chk48hs = new javax.swing.JCheckBox();
        chk24hs = new javax.swing.JCheckBox();
        chkVC = new javax.swing.JCheckBox();
        chkCAP = new javax.swing.JCheckBox();
        comboChequeEstado = new javax.swing.JComboBox();
        chkEstado = new javax.swing.JCheckBox();
        jLabel6 = new javax.swing.JLabel();
        comboChequeEstadoDestino = new javax.swing.JComboBox();
        chkEnableEstadosDestino = new javax.swing.JCheckBox();
        jLabel7 = new javax.swing.JLabel();
        comboCuentaBancoDestino = new javax.swing.JComboBox();
        chkEnableComboCuentaDestino = new javax.swing.JCheckBox();
        btnAplicar = new javax.swing.JButton();
        jSeparator3 = new javax.swing.JSeparator();
        chkEnableCuenta = new javax.swing.JCheckBox();
        comboCuentaBanco = new javax.swing.JComboBox();
        jPanel2 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        lblSelecTotalCheques = new javax.swing.JLabel();
        lblSelecTotalVC = new javax.swing.JLabel();
        lblSelecTotalCap = new javax.swing.JLabel();
        lblSelecTotalImporte = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("...: Liquidación de Cheques :...");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formWindowActivated(evt);
            }
        });

        pnlCliente.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Seleccione cliente", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 2, 12))); // NOI18N

        comboClientes.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                comboClientesItemStateChanged(evt);
            }
        });

        btnBuscar.setText("Buscar");
        btnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout pnlClienteLayout = new javax.swing.GroupLayout(pnlCliente);
        pnlCliente.setLayout(pnlClienteLayout);
        pnlClienteLayout.setHorizontalGroup(
            pnlClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlClienteLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(comboClientes, javax.swing.GroupLayout.PREFERRED_SIZE, 205, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(btnBuscar)
                .addContainerGap(23, Short.MAX_VALUE))
        );
        pnlClienteLayout.setVerticalGroup(
            pnlClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlClienteLayout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addGroup(pnlClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(comboClientes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnBuscar))
                .addContainerGap(26, Short.MAX_VALUE))
        );

        tblCheque.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        tblCheque.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Bolsa", "Cheque.Nro", "Tipo ", "Fecha alta", "Cliente", "Banco", "Cta. Bancaria", "Origen", "Importe", "Com", "Usuario", "Estado"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblCheque.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_ALL_COLUMNS);
        tblCheque.setSelectionMode(javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        //TableColumn col = tblCheque.getColumnModel().getColumn(11);
        //col.setCellEditor(new MyComboBoxEditor(ChequeEstadoServices.ESTADOS_PARA_LIQUIDACION).getEditor());
        //DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
        //renderer.setToolTipText("Click para cambiar de estado");
        //col.setCellRenderer(renderer);
        tblCheque.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblChequeMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tblCheque);

        btnLiquidar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/payment.png"))); // NOI18N
        btnLiquidar.setText("Liquidar");
        btnLiquidar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLiquidarActionPerformed(evt);
            }
        });

        lblResultadoBuscar.setFont(new java.awt.Font("Tahoma", 3, 12)); // NOI18N
        lblResultadoBuscar.setText("jLabel1");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Liquidación ", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 2, 12))); // NOI18N

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel1.setText("Fecha liquidación:");

        lblFechaLiquidacion.setText("28/06/2013");

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel3.setText("CAP:");

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel4.setText("VC:");

        lblTotalCAP.setText("$0");

        lblTotalVC.setText("$0");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addGap(18, 18, 18)
                        .addComponent(lblTotalCAP)))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblFechaLiquidacion)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(lblTotalVC)
                        .addGap(1, 1, 1)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(lblFechaLiquidacion))
                .addGap(18, 18, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblTotalCAP)
                    .addComponent(lblTotalVC))
                .addContainerGap())
        );

        jPanel3.setEnabled(false);
        jPanel3.setPreferredSize(new java.awt.Dimension(539, 230));

        chkEnableBanco.setText("De este banco");
        chkEnableBanco.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chkEnableBancoActionPerformed(evt);
            }
        });

        comboBanco.setEnabled(false);
        comboBanco.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                comboBancoItemStateChanged(evt);
            }
        });

        chkCaja.setText("Caja");
        chkCaja.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chkCajaActionPerformed(evt);
            }
        });

        chk48hs.setText("48 hs");
        chk48hs.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chk48hsActionPerformed(evt);
            }
        });

        chk24hs.setText("24 hs");
        chk24hs.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chk24hsActionPerformed(evt);
            }
        });

        chkVC.setText("VC");
        chkVC.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chkVCActionPerformed(evt);
            }
        });

        chkCAP.setText("CAP");
        chkCAP.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chkCAPActionPerformed(evt);
            }
        });

        comboChequeEstado.setEnabled(false);
        comboChequeEstado.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                comboChequeEstadoItemStateChanged(evt);
            }
        });

        chkEstado.setText("Estado");
        chkEstado.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chkEstadoActionPerformed(evt);
            }
        });

        jLabel6.setText("Marcarlos como");

        chkEnableEstadosDestino.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chkEnableEstadosDestinoActionPerformed(evt);
            }
        });

        jLabel7.setText("Asignar a cuenta");

        chkEnableComboCuentaDestino.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chkEnableComboCuentaDestinoActionPerformed(evt);
            }
        });

        btnAplicar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/check.png"))); // NOI18N
        btnAplicar.setText("Aplicar");
        btnAplicar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAplicarActionPerformed(evt);
            }
        });

        chkEnableCuenta.setText("Cuenta");
        chkEnableCuenta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chkEnableCuentaActionPerformed(evt);
            }
        });

        comboCuentaBanco.setEnabled(false);
        comboCuentaBanco.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                comboCuentaBancoItemStateChanged(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGap(6, 6, 6)
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(comboChequeEstadoDestino, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(chkEnableEstadosDestino)
                        .addGap(14, 14, 14)
                        .addComponent(jLabel7)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(comboCuentaBancoDestino, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(chkEnableComboCuentaDestino)
                        .addGap(18, 18, 18)
                        .addComponent(btnAplicar)
                        .addContainerGap(59, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(chkCaja)
                                    .addComponent(chk48hs)
                                    .addComponent(chk24hs)
                                    .addComponent(chkVC))
                                .addGap(123, 123, 123)
                                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(chkCAP)
                                    .addGroup(jPanel3Layout.createSequentialGroup()
                                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(chkEnableBanco, javax.swing.GroupLayout.Alignment.TRAILING)
                                            .addGroup(jPanel3Layout.createSequentialGroup()
                                                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                    .addComponent(chkEnableCuenta)
                                                    .addComponent(chkEstado))
                                                .addGap(34, 34, 34)))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(comboChequeEstado, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addComponent(comboBanco, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addComponent(comboCuentaBanco, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                            .addComponent(jSeparator3))
                        .addContainerGap())))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnAplicar)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(comboBanco, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(chkEnableBanco)
                            .addComponent(chkCaja))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(chk48hs)
                            .addComponent(chkEstado)
                            .addComponent(comboChequeEstado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(chk24hs)
                            .addComponent(chkEnableCuenta)
                            .addComponent(comboCuentaBanco, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(chkVC)
                            .addComponent(chkCAP))
                        .addGap(9, 9, 9)
                        .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(comboCuentaBancoDestino, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(jLabel7))
                                    .addGroup(jPanel3Layout.createSequentialGroup()
                                        .addGap(1, 1, 1)
                                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                            .addComponent(jLabel6)
                                            .addComponent(comboChequeEstadoDestino, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                    .addComponent(chkEnableEstadosDestino)))
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addGap(6, 6, 6)
                                .addComponent(chkEnableComboCuentaDestino)))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jTabbedPane1.addTab("Editar liquidación", jPanel3);

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Selección"));

        jLabel2.setText("Cheques :");

        jLabel5.setText("VC:");

        jLabel8.setText("CAP:");

        jLabel9.setText("Total importe: ");

        lblSelecTotalCheques.setText("0");

        lblSelecTotalVC.setText("0");

        lblSelecTotalCap.setText("0");

        lblSelecTotalImporte.setText("0");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel5)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblSelecTotalCheques)
                    .addComponent(lblSelecTotalVC))
                .addGap(84, 84, 84)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel8)
                        .addGap(18, 18, 18)
                        .addComponent(lblSelecTotalCap))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel9)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(lblSelecTotalImporte)))
                .addContainerGap(97, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel9)
                    .addComponent(lblSelecTotalCheques)
                    .addComponent(lblSelecTotalImporte))
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(lblSelecTotalVC)
                    .addComponent(jLabel8)
                    .addComponent(lblSelecTotalCap))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout panelContenedorLayout = new javax.swing.GroupLayout(panelContenedor);
        panelContenedor.setLayout(panelContenedorLayout);
        panelContenedorLayout.setHorizontalGroup(
            panelContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelContenedorLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(panelContenedorLayout.createSequentialGroup()
                        .addGroup(panelContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1)
                            .addGroup(panelContenedorLayout.createSequentialGroup()
                                .addGroup(panelContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(pnlCliente, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addGap(18, 18, 18)
                                .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 700, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 29, Short.MAX_VALUE)))
                        .addContainerGap())
                    .addGroup(panelContenedorLayout.createSequentialGroup()
                        .addComponent(btnLiquidar)
                        .addGap(89, 89, 89)
                        .addComponent(lblResultadoBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 352, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(37, 37, 37))))
        );
        panelContenedorLayout.setVerticalGroup(
            panelContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelContenedorLayout.createSequentialGroup()
                .addGroup(panelContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(panelContenedorLayout.createSequentialGroup()
                        .addComponent(pnlCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 88, Short.MAX_VALUE))
                    .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 302, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(panelContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(panelContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(btnLiquidar)
                        .addComponent(lblResultadoBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(panelContenedor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(panelContenedor, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    
    
    public static List<Cheque> getChequeList() {
        return chequeList;
    }

    public static void setChequeList(List<Cheque> chequeList) {
        frmLiquidacion.chequeList = chequeList;
    }
    
    
    private void btnLiquidarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLiquidarActionPerformed
            if(!chequeList.isEmpty()){
                if(!cuentaSinAsignar(chequeList)){
                    DefaultTableModel model         = (DefaultTableModel)tblCheque.getModel();
                    Vector<Vector> liquidacionData  = model.getDataVector();
                    modalPanelAddLiquidacion panelLiquidacion = new modalPanelAddLiquidacion(this, true);
                    panelLiquidacion.setLocationRelativeTo(this);
                    panelLiquidacion.setCliente((Cliente)liquidacionData.get(0).get(NOMBRE_CLIENTE));
                    panelLiquidacion.setChequeList(chequeList);
                    panelLiquidacion.setFechaLiquidacion(AppSession.getFechaDeLiquidacion().getTime());
                    panelLiquidacion.setVisible(true); 
                }else{
                    JOptionPane.showMessageDialog(this,UIMessages.getErrorMessage("chequesWithoutAccount"), UIMessages.getErrorMessage("defaultErrorTitle"), JOptionPane.ERROR_MESSAGE);
                }
                
                } else {
                    JOptionPane.showMessageDialog(this, UIMessages.getErrorMessage("noChequeResults"), UIMessages.getErrorMessage("defaultErrorTitle"), JOptionPane.ERROR_MESSAGE);
            }  
                
    }//GEN-LAST:event_btnLiquidarActionPerformed
  
    
    private boolean cuentaSinAsignar(List<Cheque> list){
        boolean tieneSinAsignar = false;
        
            for(Cheque cheque : list){
                if(cheque.getChequeTipoId().getId() == ChequeTipoServices.CHEQUE_48_HS || 
                   cheque.getChequeTipoId().getId() == ChequeTipoServices.CHEQUE_24_HS)
                    {
                       if(cheque.getCuentaBancoId().getId() == CTA_SIN_ASIGNAR){
                        tieneSinAsignar = true;
                        break;
                    }
                }
            }
            
            return tieneSinAsignar;
        }
    
    
    
    private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed
            buscarLiquidaciones();      
    }//GEN-LAST:event_btnBuscarActionPerformed

    private void buscarLiquidaciones(){
        if(comboClientes.getSelectedIndex()!= 0){  
            JComboBoxModel model                  = (JComboBoxModel) comboClientes.getSelectedItem();
            int cliente_id                        = Integer.valueOf(model.getValue());
            Cliente cliente                       = clienteServices.get(cliente_id);
            BolsaChequeServices bolsaChequeServices   = (BolsaChequeServices)SpringUtils.getBean("bolsaChequeServices");
            chequeList                            = bolsaChequeServices.getChequesToLiquidFromListOfBolsaChequeByCliente(cliente,AppSession.getFechaDeLiquidacion());
            cargarTablaCheque(chequeList);
            comboBanco.setModel(modelComboBanco);
            comboCuentaBanco.setModel(modelComboCuenta);
            
                if(chequeList.isEmpty()){
                          JOptionPane.showMessageDialog(this, UIMessages.getErrorMessage("noChequesToLiquid"), 
                                                  UIMessages.getInfoMessage("defaultInfoTitle"), JOptionPane.INFORMATION_MESSAGE);
                                limpiarDatos();
                          
                } else       {
                                mostrarLabelDeResultado(chequeList.size(), true);
                                activarDesactivarPanel(true);
                                List<String> bancoIdList = FilterCheque.getBancosIdByChequeList(chequeList);
                                UserInterfaceHelper.refreshJComboBoxWithThisList(bancoIdList, comboBanco,UserInterfaceHelper.BY_VALUE);
                                List<String> cuentaBancoIdList = FilterCheque.getCuentaBancoIdByChequeList(chequeList);
                                UserInterfaceHelper.refreshJComboBoxWithThisList(cuentaBancoIdList, comboCuentaBanco,UserInterfaceHelper.BY_VALUE);
                               }
            } else {
                    JOptionPane.showMessageDialog(this, UIMessages.getErrorMessage("requiredSelectedCliente"), UIMessages.getErrorMessage("defaultErrorTitle"), JOptionPane.ERROR_MESSAGE);
                    limpiarDatos();
            }
    }
    
    
    
    
    
    
    private void btnAplicarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAplicarActionPerformed
        int indices[]                       = tblCheque.getSelectedRows();
        if(indices.length > 0){
            /*Debe haber seleccionado al menos una cuenta o un estado para asignar */
            if(chkEnableEstadosDestino.isSelected() || chkEnableComboCuentaDestino.isSelected()){
        
            DefaultTableModel tablaModel        = (DefaultTableModel)tblCheque.getModel();
            List<Cheque> chequesToUpdateList = new ArrayList<>();
        for (int i=0; i < indices.length; i++){
                Cheque cheque = (Cheque)tablaModel.getValueAt(indices[i], 1);
                chequesToUpdateList.add(cheque);
            }
        

        /*Recorremos todos los cheques seleccionados para el UPDATE de estados/cuentas */    
        for(Cheque chequeUpdate : chequesToUpdateList){
            int index = chequeList.indexOf(chequeUpdate);
            if( index != NO_EXISTE){
                if(chkEnableEstadosDestino.isSelected()){
                    JComboBoxModel comboEstadoSelected = (JComboBoxModel)comboChequeEstadoDestino.getSelectedItem();
                    ChequeEstado nuevoEstadoCheque = chequeEstadoServices.get(Integer.parseInt(comboEstadoSelected.getValue()));
                   
                    /* Si es pendiente vamos asignarle una fecha nueva de pendiente utilizando el CalendarioServices */
                    if (nuevoEstadoCheque.getId() == ChequeEstadoServices.CHEQUE_PENDIENTE) {
                        Calendar fechaPendiente = calendarioServices.calcularSiguienteDiaHabil();
                        chequeUpdate.setFechaPendiente(fechaPendiente.getTime());
                        chequeUpdate.setFechaUpdate(new Date());
                        log.info("--> Próximo día habil : " + fechaPendiente.getTime());
                        log.info("--> Fecha pendiente asignada!");
                    }else {
                        chequeUpdate.setFechaPendiente(null);
                    }
                    chequeUpdate.setChequeEstadoId(nuevoEstadoCheque);
                }

                /* Obtenemos la cuenta destino seleccionada y se la asignamos */
                if(chkEnableComboCuentaDestino.isSelected()){
                    JComboBoxModel comboCuentaSelected = (JComboBoxModel)comboCuentaBancoDestino.getSelectedItem();
                    CuentaBanco nuevoEstadoCheque = cuentaBancoServices.get(Integer.parseInt(comboCuentaSelected.getValue()));
                    chequeUpdate.setCuentaBancoId(nuevoEstadoCheque);
                }

                chequeList.set(index, chequeUpdate);
            }
        }
        
        cargarTablaCheque(chequeList);
        /* Volvemos a seleccionar en la tabla los cheques involucrados en este cambio */
        tblCheque.clearSelection();
        ListSelectionModel selection = tblCheque.getSelectionModel();
        for (int i = 0; i < indices.length; i++) {
             selection.addSelectionInterval(indices[i], indices[i]);
         }
         tblCheque.setSelectionModel(selection);
         tblCheque.repaint();
         
         /*Actualizamos el combo de Cuentas nuevamente */
         List<String> cuentaBancoIdList = FilterCheque.getCuentaBancoIdByChequeList(chequeList);
         
         comboCuentaBanco.setModel(modelComboCuenta);
         UserInterfaceHelper.refreshJComboBoxWithThisList(cuentaBancoIdList, comboCuentaBanco,UserInterfaceHelper.BY_VALUE);
         reiniciarPanel();
        
        }else{
                JOptionPane.showMessageDialog(this, UIMessages.getInfoMessage("requiredEstadoOrCuentaToUpdate"), UIMessages.getInfoMessage("defaultInfoTitle"), JOptionPane.INFORMATION_MESSAGE);
            }
        } else {
            JOptionPane.showMessageDialog(this, UIMessages.getErrorMessage("requiredAtLeastSelectedCheque"), UIMessages.getInfoMessage("defaultInfoTitle"), JOptionPane.INFORMATION_MESSAGE);
        }
    }//GEN-LAST:event_btnAplicarActionPerformed

    private void limpiarDatos(){
        DefaultTableModel model     = (DefaultTableModel) tblCheque.getModel();
        model.getDataVector().clear();
        tblCheque.setModel(model);
        tblCheque.repaint();
        tblCheque.getSelectionModel().clearSelection();
        mostrarLabelDeResultado(0, false);
        activarDesactivarPanel(false);
        lblSelecTotalCap.setText("0");
        lblSelecTotalCheques.setText("0");
        lblSelecTotalImporte.setText("0");
        lblSelecTotalVC.setText("0");
        lblTotalCAP.setText("0");
        lblTotalVC.setText("0");
        comboClientes.setSelectedIndex(0);
    }
    
    
    
    private void activarDesactivarPanel(boolean enable){
        chkCaja.setEnabled(enable);
        chk48hs.setEnabled(enable);
        chk24hs.setEnabled(enable);
        chkVC.setEnabled(enable);
        chkCAP.setEnabled(enable);
        chkEnableBanco.setEnabled(enable);
        chkEstado.setEnabled(enable);
        chkEnableCuenta.setEnabled(enable);
        
        
        if(!enable){
            chkEnableComboCuentaDestino.setSelected(false);
            chkEnableComboCuentaDestino.setSelected(false);
        }
        
        chkEnableComboCuentaDestino.setEnabled(enable);
        chkEnableEstadosDestino.setEnabled(enable);
        comboChequeEstadoDestino.setEnabled(enable);
        comboCuentaBancoDestino.setEnabled(enable);
        
        btnAplicar.setEnabled(enable);
        btnLiquidar.setEnabled(enable);
    }
    
    
    private void reiniciarPanel(){
        
        chkCaja.setSelected(false);
        chk48hs.setSelected(false);
        chk24hs.setSelected(false);
        
        chkEnableBanco.setSelected(false);
        comboBanco.setSelectedIndex(0);
        comboBanco.setEnabled(false);
        
        chkEstado.setSelected(false);
        comboChequeEstado.setSelectedIndex(0);
        comboChequeEstado.setEnabled(false);
        
        chkEnableCuenta.setSelected(false);
        comboCuentaBanco.setSelectedIndex(0);
        comboCuentaBanco.setEnabled(false);
        
        chkVC.setSelected(false);
        chkCAP.setSelected(false);
    }
    
    
    
    private void chkEnableComboCuentaDestinoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkEnableComboCuentaDestinoActionPerformed
        if(chkEnableComboCuentaDestino.isSelected()){
            comboCuentaBancoDestino.setEnabled(true);
        }else {
            comboCuentaBancoDestino.setEnabled(false);
        }
    }//GEN-LAST:event_chkEnableComboCuentaDestinoActionPerformed

    private void chkEnableEstadosDestinoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkEnableEstadosDestinoActionPerformed
        if(chkEnableEstadosDestino.isSelected()){
            comboChequeEstadoDestino.setEnabled(true);
        }else{
            comboChequeEstadoDestino.setEnabled(false);
        }
    }//GEN-LAST:event_chkEnableEstadosDestinoActionPerformed

    private void chkEstadoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkEstadoActionPerformed
        if(chkEstado.isSelected()){
            comboChequeEstado.setEnabled(true);
        } else {
            comboChequeEstado.setEnabled(false);
            comboBanco.setSelectedIndex(0);
            chequeFilteredList.clear();
            chequeFilteredList.addAll(chequeList);
            filtrarCheques();
        }
    }//GEN-LAST:event_chkEstadoActionPerformed

    private void comboChequeEstadoItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_comboChequeEstadoItemStateChanged
        chequeFilteredList.clear();
        chequeFilteredList.addAll(chequeList);
        if(comboChequeEstado.getSelectedIndex() != 0){
            filtrarCheques();
        }
    }//GEN-LAST:event_comboChequeEstadoItemStateChanged

    private void chkCAPActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkCAPActionPerformed
        chequeFilteredList.clear();
        chequeFilteredList.addAll(chequeList);
        filtrarCheques();
    }//GEN-LAST:event_chkCAPActionPerformed

    private void chkVCActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkVCActionPerformed
        chequeFilteredList.clear();
        chequeFilteredList.addAll(chequeList);
        filtrarCheques();
    }//GEN-LAST:event_chkVCActionPerformed

    private void chk24hsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chk24hsActionPerformed
        chequeFilteredList.clear();
        chequeFilteredList.addAll(chequeList);
        filtrarCheques();
    }//GEN-LAST:event_chk24hsActionPerformed

    private void chk48hsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chk48hsActionPerformed
        chequeFilteredList.clear();
        chequeFilteredList.addAll(chequeList);
        filtrarCheques();
    }//GEN-LAST:event_chk48hsActionPerformed

    private void chkCajaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkCajaActionPerformed
        chequeFilteredList.clear();
        chequeFilteredList.addAll(chequeList);
        filtrarCheques();
    }//GEN-LAST:event_chkCajaActionPerformed

    private void comboBancoItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_comboBancoItemStateChanged
        chequeFilteredList.clear();
        chequeFilteredList.addAll(chequeList);
        if(comboBanco.getSelectedIndex() != 0){
            filtrarCheques();
        }
    }//GEN-LAST:event_comboBancoItemStateChanged

    private void chkEnableBancoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkEnableBancoActionPerformed
        if(chkEnableBanco.isSelected()){
            comboBanco.setEnabled(true);
        }else{
            comboBanco.setEnabled(false);
            comboBanco.setSelectedIndex(0);
            chequeFilteredList.clear();
            chequeFilteredList.addAll(chequeList);
            filtrarCheques();
        }
    }//GEN-LAST:event_chkEnableBancoActionPerformed

    private void tblChequeMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblChequeMouseClicked
        fromTableClick = true;
        chequeFilteredList.clear();
        chequeFilteredList.addAll(chequeList);
        filtrarCheques();
    }//GEN-LAST:event_tblChequeMouseClicked

    private void chkEnableCuentaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkEnableCuentaActionPerformed
       if(chkEnableCuenta.isSelected()){
            comboCuentaBanco.setEnabled(true);
        }else{
            comboCuentaBanco.setEnabled(false);
            comboCuentaBanco.setSelectedIndex(0);
            chequeFilteredList.clear();
            chequeFilteredList.addAll(chequeList);
            filtrarCheques();
        }
    }//GEN-LAST:event_chkEnableCuentaActionPerformed

    private void comboCuentaBancoItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_comboCuentaBancoItemStateChanged
        chequeFilteredList.clear();
        chequeFilteredList.addAll(chequeList);
        if(comboCuentaBanco.getSelectedIndex() != 0){
            filtrarCheques();
        }
    }//GEN-LAST:event_comboCuentaBancoItemStateChanged

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        actualizarComboDeClientes();
    }//GEN-LAST:event_formWindowOpened

    private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
        if(comboClientes.getSelectedIndex() > 0){
            buscarLiquidaciones();
        }
    }//GEN-LAST:event_formWindowActivated

    private void comboClientesItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_comboClientesItemStateChanged
        DefaultTableModel model     = (DefaultTableModel) tblCheque.getModel();
        model.getDataVector().removeAllElements();
        model.fireTableDataChanged();
        activarDesactivarPanel(false);
    }//GEN-LAST:event_comboClientesItemStateChanged

    
   public void actualizarComboDeClientes(){
       List<String> clientesToLiquidList = new ArrayList(clientesToLiquid);
       UserInterfaceHelper.refreshJComboBoxWithThisList(clientesToLiquidList, comboClientes, UserInterfaceHelper.BY_LABEL);
   }
           
           
           

    private void filtrarCheques(){
        boolean noFilters = true;    
        
        
        
            if(chkEnableBanco.isSelected()){
                JComboBoxModel  selectedBanco = (JComboBoxModel) comboBanco.getSelectedItem();
                chequeFilteredList = select(chequeFilteredList, FilterCheque.filterChequesByBanco(Integer.parseInt(selectedBanco.getValue())));
                noFilters = false;
            }
        
            
           if(chkEstado.isSelected()){
               JComboBoxModel  selectedEstado = (JComboBoxModel) comboChequeEstado.getSelectedItem();
               chequeFilteredList = select(chequeFilteredList,FilterCheque.filterChequesByEstado(Integer.parseInt(selectedEstado.getValue())));
               noFilters = false;
           }
           
           if(chkEnableCuenta.isSelected()){
               JComboBoxModel  selectedEstado = (JComboBoxModel) comboCuentaBanco.getSelectedItem();
               chequeFilteredList = select(chequeFilteredList,FilterCheque.filterChequesByCuenta(Integer.parseInt(selectedEstado.getValue())));
               noFilters = false;
           }
            
           if(chk48hs.isSelected()){
               chequeFilteredList  = select(chequeFilteredList, FilterCheque.filterChequesByTipo(ChequeTipoServices.CHEQUE_48_HS));
               noFilters = false;
           }
           
           if(chk24hs.isSelected()){
               chequeFilteredList = select(chequeFilteredList,FilterCheque.filterChequesByTipo(ChequeTipoServices.CHEQUE_24_HS));
               noFilters = false;
           }
           
            
           if(chkVC.isSelected()){
               chequeFilteredList = select(chequeFilteredList,FilterCheque.filterChequesByOrigen(ChequeServices.ORIGEN_VC));
               noFilters = false;
           } 
           
           if(chkCAP.isSelected()){
               chequeFilteredList = select(chequeFilteredList,FilterCheque.filterChequesByOrigen(ChequeServices.ORIGEN_CAP_BSAS));
               noFilters = false;
           }
           

           
           if(fromTableClick){
             if(chequeFilteredList.size() > tblCheque.getSelectedRows().length){
                eliminarChequesAlFiltro(tblCheque.getSelectedRows());
                noFilters = false;
                }
            
             if(chequeFilteredList.size() <= tblCheque.getSelectedRows().length){
                agregarChequesAlFiltro(tblCheque.getSelectedRows());
                noFilters = false;
                } 
           }
           
          
           if(noFilters){
               tblCheque.clearSelection();
               tblCheque.repaint();
               chequeFilteredList.clear();
               sumarTotalesDeSeleccion(chequeFilteredList);
           } else {
                filtrarChequesEnTablaCheque(chequeList, chequeFilteredList);
                sumarTotalesDeSeleccion(chequeFilteredList);
           }
           
           fromTableClick = false;
    }
    
    private void agregarChequesAlFiltro(int chequesSelected[]){
        for (int i = 0; i < chequesSelected.length; i++) {
            Cheque selectedCheque = (Cheque)tblCheque.getValueAt(chequesSelected[i], 1);
            if(!chequeFilteredList.contains(selectedCheque)){
                chequeFilteredList.add(selectedCheque);
            }
        }
    }
    
    
    
    private void eliminarChequesAlFiltro(int chequesSelected[]){
        System.out.println("Eliminando  cheques del filtros");
        List<Cheque> temporaryList = new ArrayList<>();
        
        for (int i = 0; i < chequesSelected.length; i++) {
            Cheque selectedCheque = (Cheque)tblCheque.getValueAt(chequesSelected[i], 1);
            temporaryList.add(selectedCheque);
        }
        
        chequeFilteredList.clear();
        chequeFilteredList.addAll(temporaryList);
    }
   
    private void sumarTotalesDeSeleccion(List<Cheque> chequeFilteredList){
        int totalCheques    = 0;    // El número total de cheques seleccionados
        int totalChequesVC  = 0;    // El número total de cheques VC seleccionados
        int totalChequesCAP = 0;    // El número total de cheques CAP seleccionados
        double importeTotal = 0;    // La suma de los importes de todos los cheques seleccionados
        
        if(!chequeFilteredList.isEmpty()){
            for(Cheque cheque : chequeFilteredList){
                if(cheque.getOrigen().equals(ChequeServices.ORIGEN_CAP_BSAS)){
                    totalChequesCAP++;
                }else{
                    totalChequesVC++;
                }
                importeTotal += cheque.getImporte().doubleValue();
            }
        }
        
        totalCheques = totalChequesCAP + totalChequesVC;
        /*Seteamos los totales calculados en los JLabel */
        lblSelecTotalCap.setText(String.valueOf(totalChequesCAP));
        lblSelecTotalVC.setText(String.valueOf(totalChequesVC));
        lblSelecTotalCheques.setText(String.valueOf(totalCheques));
        lblSelecTotalImporte.setText(Formato.decimalComaMilesConSigno(importeTotal));  
    }   
    private void cargarDatos(){
        comboClientes.setModel(clienteServices.combo());
        lblFechaLiquidacion.setText(Formato.cambiarFechaAFormatoLocal(AppSession.getFechaDeLiquidacion().getTime()));
    }
    
    
    public static void cargarTablaCheque(List<Cheque> listado){
        DateFormat format           = DateFormat.getDateInstance();
        DefaultTableModel model     = (DefaultTableModel) tblCheque.getModel();
        model.getDataVector().clear();
        
        double totalImporteCAP = 0;
        double totalImporteVC  = 0;
        
        for(Cheque cheque : listado){
            model.addRow(new Object[]{cheque.getBolsaChequeId().getId(),cheque,cheque.getChequeTipoId().getTipo(),
                format.format(cheque.getBolsaChequeId().getFechaAlta()),cheque.getBolsaChequeId().getClienteId(),cheque.getBancoId().getNombre(),
                cheque.getCuentaBancoId().getNombre(),cheque.getOrigen(),Formato.decimalComaMilesConSigno(cheque.getImporte().doubleValue()),cheque.getComision().floatValue(),
                cheque.getBolsaChequeId().getUsuarioId().getNombre(), cheque.getChequeEstadoId().getNombre()} );
            
            if(cheque.getOrigen().equals(ChequeServices.ORIGEN_CAP_BSAS)){
                totalImporteCAP += cheque.getImporte().doubleValue();
            } else {
                totalImporteVC  += cheque.getImporte().doubleValue();
            }
        }
                
        tblCheque.setModel(model);
        tblCheque.repaint();
        tblCheque.getSelectionModel().clearSelection();
        lblTotalCAP.setText(Formato.decimalComaMilesConSigno(totalImporteCAP));
        lblTotalVC.setText(Formato.decimalComaMilesConSigno(totalImporteVC));
    }
    
    
    public static void filtrarChequesEnTablaCheque(List<Cheque> listado,List<Cheque> chequeFilteredList){
        List<Integer> selectedIndexList = new ArrayList();
        tblCheque.clearSelection();
        
        
        
        for(Cheque chequeToSelect : chequeFilteredList){
            int index = 0 ;
            for(Cheque cheque : listado){
                if(chequeToSelect.getCodigoString().equals(cheque.getCodigoString())){
                    selectedIndexList.add(index);
                }
                index++;
            }
        }
        
       ListSelectionModel selection = tblCheque.getSelectionModel();
       
       for(Integer readIndex : selectedIndexList){
            selection.addSelectionInterval(readIndex, readIndex);
        }
       
       tblCheque.setSelectionModel(selection);
       tblCheque.repaint();

    }
    
    
    
    private void valoresPorDefecto(){
        this.setIconImage(new ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/moneybox.png")).getImage());
        modelComboBanco = bancoServices.combo();
        modelComboCuenta = cuentaBancoServices.combo();
        comboChequeEstadoDestino.setEnabled(false);
        comboCuentaBancoDestino.setEnabled(false);
        cargarCombos();
        activarDesactivarPanel(false);
        lblResultadoBuscar.setVisible(false);
    }
    
    
    
    private void cargarCombos(){
         comboBanco.setModel(modelComboBanco);
         comboChequeEstado.setModel(chequeEstadoServices.combo(ChequeEstadoServices.ESTADOS_PARA_EDITAR_LIQUID));
         comboChequeEstadoDestino.setModel(chequeEstadoServices.combo(ChequeEstadoServices.ESTADOS_PARA_LIQUIDACION));
         comboCuentaBancoDestino.setModel(cuentaBancoServices.combo());
         comboCuentaBanco.setModel(cuentaBancoServices.combo());
    }
    
    public void mostrarLabelDeResultado(int size,boolean visible){
        lblResultadoBuscar.setText("Se encontraron "+size+" cheques para liquidar");
        lblResultadoBuscar.setVisible(true); 
    }

    /**
     * @return the clientesToLiquid
     */
    public Set<String> getClientesToLiquid() {
        return clientesToLiquid;
    }

    /**
     * @param clientesToLiquid the clientesToLiquid to set
     */
    public void setClientesToLiquid(Set<String> clientesToLiquid) {
        this.clientesToLiquid = clientesToLiquid;
    }
   
    public static void main(String args[]) {

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new frmLiquidacion().setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAplicar;
    protected static javax.swing.JButton btnBuscar;
    private javax.swing.JButton btnLiquidar;
    private javax.swing.JCheckBox chk24hs;
    private javax.swing.JCheckBox chk48hs;
    private javax.swing.JCheckBox chkCAP;
    private javax.swing.JCheckBox chkCaja;
    private javax.swing.JCheckBox chkEnableBanco;
    private javax.swing.JCheckBox chkEnableComboCuentaDestino;
    private javax.swing.JCheckBox chkEnableCuenta;
    private javax.swing.JCheckBox chkEnableEstadosDestino;
    private javax.swing.JCheckBox chkEstado;
    private javax.swing.JCheckBox chkVC;
    private javax.swing.JComboBox comboBanco;
    private javax.swing.JComboBox comboChequeEstado;
    private javax.swing.JComboBox comboChequeEstadoDestino;
    private javax.swing.JComboBox comboClientes;
    private javax.swing.JComboBox comboCuentaBanco;
    private javax.swing.JComboBox comboCuentaBancoDestino;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator3;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JLabel lblFechaLiquidacion;
    private javax.swing.JLabel lblResultadoBuscar;
    private javax.swing.JLabel lblSelecTotalCap;
    private javax.swing.JLabel lblSelecTotalCheques;
    private javax.swing.JLabel lblSelecTotalImporte;
    private javax.swing.JLabel lblSelecTotalVC;
    private static javax.swing.JLabel lblTotalCAP;
    private static javax.swing.JLabel lblTotalVC;
    private javax.swing.JPanel panelContenedor;
    private javax.swing.JPanel pnlCliente;
    protected static javax.swing.JTable tblCheque;
    // End of variables declaration//GEN-END:variables

    
}
